﻿using System.Windows.Forms;
using System.Xml;
using UIShell.OSGi;

namespace Pasys.PresentationCore.WinForms
{
    public class ContextMenuStuffer : BuilderBase<MenuCreator>
    {
        private ContextMenuStrip _contextMenuStrip = null;
        public ContextMenuStuffer(ContextMenuStrip contextMenuStrip)
        {
            _contextMenuStrip = contextMenuStrip;
        }

        public override void Build(XmlNode xmlNode, IBundle owner)
        {
            if (_contextMenuStrip == null)
            {
                return;
            }

            ToolbarCreateOptions opts;
            bool addSelf= xmlNode.Name != "ToolStrip";
            ToolStripItem newItem = ToolbarItemBuilder.Build(xmlNode, owner, out opts);
            addItems(newItem, opts, addSelf);
        }

        private void addItems(ToolStripItem newItem, ToolbarCreateOptions opts,bool addSelf)
        {
            var parentItem = _contextMenuStrip;

            var children = newItem as ToolStripDropDownItem;
            switch (opts.CreateType)
            {
                case MenuCreateType.Insert:
                    if (addSelf)
                    {
                        parentItem.Items.Insert(0, newItem);
                    }
                    else
                    {
                        for (int i = children.DropDownItems.Count - 1; i >= 0; i--)
                        {
                            parentItem.Items.Insert(0, (ToolStripItem)children.DropDownItems[i]);
                        }
                    }
                    break;
                case MenuCreateType.Append:
                default:
                    if (addSelf)
                    {
                        parentItem.Items.Add(newItem);
                    }
                    else
                    {
                        while (children.DropDownItems.Count > 0)
                        {
                            parentItem.Items.Add((ToolStripItem)children.DropDownItems[0]);
                        }
                    }
                    break;
            }
        }
    }
}
